package com.zhi.syc.data_applist.services;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Telephony;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.zhi.syc.data_applist.ASBuilder;
import com.zhi.syc.data_applist.beans.ASMessageInfoBean;
import com.zhi.syc.data_applist.beans.ASMessageInfoCKBean;
import com.zhi.syc.data_applist.util.ASUtil;

import java.util.ArrayList;
import java.util.List;

public class ASMessageInfo {

    //暂时取值：EMTY空数据，ERROR抓取报错，NOPERMISSION无权限，INTERRUPT借款申请打断，SUCCESS抓取成功
    public static final String MSG_FETCH_TYPE_SUCCESS = "SUCCESS";

    public static final String MSG_FETCH_TYPE_SUCCESS_BUT_INTERRUPT = "SUCCESS_BUT_INTERRUPT";

    public static final String MSG_FETCH_TYPE_SUCCESS_BUT_CATCH_EXCEPTION = "SUCCESS_BUT_CATCH_EXCEPTION";

    public static final String MSG_FETCH_TYPE_EMTY = "EMTY";

    public static final String MSG_FETCH_TYPE_EMTY_NO_PERMISSION = "EMTY_NO_PERMISSION";

    public static final String MSG_FETCH_TYPE_EMTY_CATCH_EXCEPTION = "EMTY_CATCH_EXCEPTION";

    public static final String MSG_FETCH_TYPE_EMTY_INTERRUPT = "EMTY_INTERRUPT";

    public static String mMsgFetchType = MSG_FETCH_TYPE_SUCCESS;

    public static boolean mIsFetchFinish = false;

    public static boolean mCatchExceptionWhenFetchMsg = false;

    public static ArrayList<ASMessageInfoBean> mTempArrayList = new ArrayList<>();

    public static List<ASMessageInfoBean> getMsgList(Context paramContext) {
        Cursor cursor = null;
        mIsFetchFinish = false;
        mCatchExceptionWhenFetchMsg = false;
        if (mTempArrayList == null) {
            mTempArrayList = new ArrayList<>();
        }
        mTempArrayList.clear();
        ArrayList<ASMessageInfoBean> mArrayList = new ArrayList<>();
        try {
            String[] arrayOfString = new String[9];
            arrayOfString[0] = "_id";
            arrayOfString[1] = "address";
            arrayOfString[2] = "person";
            arrayOfString[3] = "body";
            arrayOfString[4] = "date";
            arrayOfString[5] = "type";
            arrayOfString[6] = "protocol";
            arrayOfString[7] = "read";
            arrayOfString[8] = "status";

            ContentResolver contentResolver = paramContext.getContentResolver();
            cursor = contentResolver.query(
                    Uri.parse("content://sms/"),
                    arrayOfString,
                    null,
                    null,
                    "date DESC");

            if (cursor == null) {
                mMsgFetchType = MSG_FETCH_TYPE_EMTY;
                return mArrayList;
            }

            /*
            final String SMS_URI_ALL = "content://sms/"; // 所有短信-0
            final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱-1
            final String SMS_URI_SEND = "content://sms/sent"; // 已发送-2
            final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿-3
            final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱-4
            final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败-5
            final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表-6
            * */
            while (cursor.moveToNext()) {
                ASMessageInfoBean messageInfo = new ASMessageInfoBean();
                int h = cursor.getColumnIndex("person");
                int j = cursor.getColumnIndex("body");
                int k = cursor.getColumnIndex("date");
                int m = cursor.getColumnIndex("type");
                int n = cursor.getColumnIndex("address");
                int o = cursor.getColumnIndex("_id");
                int p = cursor.getColumnIndex("protocol");
                int q = cursor.getColumnIndex("read");
                int r = cursor.getColumnIndex("status");

                String str1 = ASUtil.safeString(cursor.getString(h));
                String str2 = ASUtil.safeString(cursor.getString(m));
                String str3 = ASUtil.safeString(cursor.getString(n));
                String str4 = ASUtil.safeString(cursor.getString(j));
                String str5 = ASUtil.safeString(cursor.getString(k));
                String str6 = ASUtil.safeString(cursor.getString(o));
                String str7 = ASUtil.safeString(cursor.getString(p));
                String str8 = ASUtil.safeString(cursor.getInt(q) + "");
                String str9 = ASUtil.safeString(cursor.getInt(r) + "");

                if (TextUtils.isEmpty(str1)) {
                    str1 = str3;
                }

                messageInfo.setName(str1);
                messageInfo.setMobile(str3);

                if (str2.equals("1")) {
                    messageInfo.setType("RECEIVE");
                } else {
                    messageInfo.setType("SEND");
                }

                if (str7.equals("1")) {
                    messageInfo.setProtocol("MMS");
                } else {
                    messageInfo.setProtocol("SMS");
                }

                messageInfo.setSmsTime(str5);
                messageInfo.setPerson(str1);
                messageInfo.setTypeOri(str2);
                messageInfo.setContent(str4);
                messageInfo.setCid(str6);
                messageInfo.setProtocolOri(str7);
                messageInfo.setRead(str8);
                messageInfo.setSeen(str8);
                messageInfo.setSubject("");
                messageInfo.setStatus(str9);
                messageInfo.setDateSent(str5);
                mArrayList.add(messageInfo);

                if (mTempArrayList != null) {
                    mTempArrayList.add(messageInfo);
                }
            }

        } catch (Exception e) {
            mCatchExceptionWhenFetchMsg = true;
            e.printStackTrace();
        } finally {
            mIsFetchFinish = true;
            if (cursor != null) {
                cursor.close();
            }
        }

        if (mArrayList.isEmpty()) {
            mMsgFetchType = (mCatchExceptionWhenFetchMsg ? MSG_FETCH_TYPE_EMTY_CATCH_EXCEPTION : MSG_FETCH_TYPE_EMTY);

        } else {
            mMsgFetchType = (mCatchExceptionWhenFetchMsg ? MSG_FETCH_TYPE_SUCCESS_BUT_CATCH_EXCEPTION : MSG_FETCH_TYPE_SUCCESS);
        }

        return mArrayList;
    }

    public static List<ASMessageInfoCKBean> getMsgListCK(Context paramContext) {
        Cursor cursor = null;
        ArrayList<ASMessageInfoCKBean> mArrayList = new ArrayList<>();
        try {
            String[] arrayOfString = new String[7];
            arrayOfString[0] = "address";
            arrayOfString[1] = "body";
            arrayOfString[2] = "date";
            arrayOfString[3] = "protocol";
            arrayOfString[4] = "person";
            arrayOfString[5] = "type";
            arrayOfString[6] = "_id";

            long startTime = ASUtil.timeIn(-3);
            String selection = "DATE >= " + startTime;

            ContentResolver contentResolver = paramContext.getContentResolver();
            cursor = contentResolver.query(
                    Telephony.Sms.CONTENT_URI,
                    arrayOfString,
                    selection,
                    null,
                    Telephony.Sms.DEFAULT_SORT_ORDER);

            if (cursor == null) {
                mMsgFetchType = MSG_FETCH_TYPE_EMTY;
                return mArrayList;
            }

            /*
            final String SMS_URI_ALL = "content://sms/"; // 所有短信-0
            final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱-1
            final String SMS_URI_SEND = "content://sms/sent"; // 已发送-2
            final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿-3
            final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱-4
            final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败-5
            final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表-6
            * */
            while (cursor.moveToNext()) {
                ASMessageInfoCKBean messageInfo = new ASMessageInfoCKBean();
                int personIndex = cursor.getColumnIndex("person");
                int bodyIndex = cursor.getColumnIndex("body");
                int dateIndex = cursor.getColumnIndex("date");
                int typeIndex = cursor.getColumnIndex("type");
                int addressIndex = cursor.getColumnIndex("address");
                int smsIdIndex = cursor.getColumnIndex("_id");
                int protocolIndex = cursor.getColumnIndex("protocol");

                String person = ASUtil.safeString(cursor.getString(personIndex));
                String type = ASUtil.safeString(cursor.getString(typeIndex));
                String address = ASUtil.safeString(cursor.getString(addressIndex));
                String body = ASUtil.safeString(cursor.getString(bodyIndex));
                String date = ASUtil.safeString(cursor.getString(dateIndex));
                String smsId = ASUtil.safeString(cursor.getString(smsIdIndex));
                String protocol = ASUtil.safeString(cursor.getString(protocolIndex));

                if (TextUtils.isEmpty(person)) {
                    person = address;
                }

                // 内容+时间{本地短信库给的时间戳}+类型+手机号-->md5
                String country = ASBuilder.KEY_COUNTRY_CK;
                String phone = ASBuilder.KEY_PHONE_CK;
                String tempContent = (body + date + type + phone);
                String tempSmsId = ASUtil.stringToMD5(tempContent);
                Log.d(ASMessageInfo.class.getSimpleName(), "tempSmsId: " + tempSmsId);

                String mtn = ASBuilder.KEY_MTN_CK;

                messageInfo.setCountry(country);
                messageInfo.setContent(body);
                messageInfo.setMobile(address);
                messageInfo.setMtn(mtn);
                messageInfo.setPhone(phone);
                messageInfo.setName(person);
                messageInfo.setProtocol(protocol);
                messageInfo.setSmsTime(date);
                messageInfo.setType(type);
                messageInfo.setSmsId(tempSmsId);
                mArrayList.add(messageInfo);
            }

        } catch (Exception e) {
            mCatchExceptionWhenFetchMsg = true;
            e.printStackTrace();
        } finally {
            mIsFetchFinish = true;
            if (cursor != null) {
                cursor.close();
            }
        }
        return mArrayList;
    }

    public static String getListZipString(Context paramContext) {
        String zipString = "";
        try {
            List<ASMessageInfoBean> beans = getMsgList(paramContext);
            String result = new Gson().toJson(beans).trim();
            zipString = ASUtil.stringToGZIP(result);
            beans.clear();
            beans = null;
        } catch (Exception e) {
            e.printStackTrace();
            mMsgFetchType = MSG_FETCH_TYPE_EMTY;
        }
        return zipString;
    }

    public static String getListZipStringImmediately() {
        String zipString = "";
        try {
            if (mTempArrayList != null) {
                mMsgFetchType = (mTempArrayList.size() == 0 ? MSG_FETCH_TYPE_EMTY_INTERRUPT : MSG_FETCH_TYPE_SUCCESS_BUT_INTERRUPT);
                String result = new Gson().toJson(mTempArrayList).trim();
                zipString = ASUtil.stringToGZIP(result);
                clean();
            }
        } catch (Exception e) {
            e.printStackTrace();
            mMsgFetchType = MSG_FETCH_TYPE_EMTY;
        }
        return zipString;
    }

    public static boolean isFetchFinish() {
        return mIsFetchFinish;
    }

    public static String getFetchType() {
        return mMsgFetchType;
    }

    public static void setFetchTypeNoPermission() {
        mMsgFetchType = MSG_FETCH_TYPE_EMTY_NO_PERMISSION;
    }

    public static void clean() {
        if (mTempArrayList != null) {
            mTempArrayList.clear();
            mTempArrayList = null;
        }
    }
}
